package com.jun.common.redis.pubsub;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * @author yuejun.li
 * @date 2024/8/13 16:42:09
 * redis订阅者（可以多个订阅者订阅）
 */
public abstract class RedisConsumer implements MessageListener {

    //消息监听容器
    private RedisMessageListenerContainer container;

    //消息监听适配器
    private MessageListenerAdapter messageListenerAdapter;

    public RedisConsumer(RedisMessageListenerContainer container) {
        this.container = container;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //发送消息
        onReceiveMessage(message, pattern);
    }


    /**
     * 订阅对应的频道
     * @param topic 频道名称
     */
    protected void subscribe(final String topic) {
        if (messageListenerAdapter == null) {
            messageListenerAdapter = new MessageListenerAdapter(this);
        }
        //ChannelTopic 相当于 rabbitMQ的直连交换机
        container.addMessageListener(messageListenerAdapter, new ChannelTopic(topic));
    }

    /**
     * 接收频道信息
     * @param message 消息
     * @param pattern 根据模式接收
     */
    protected abstract void onReceiveMessage(final Message message, final byte[] pattern);
}
